package com.yilin.medical.lsh;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLEncoder;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.util.EntityUtils;

import android.graphics.Bitmap;

public class MyHttpClient {

	private static final int REQUEST_TIMEOUT = 20 * 1000;// 设置请求超时10秒钟
	private static final int SO_TIMEOUT = 20 * 1000; // 设置等待数据超时时间10秒钟

	private static final String encode = "UTF-8";


	/**
	 * post 请求
	 * 
	 * @param strUrl
	 * @param params
	 * @return
	 * @throws SimpleException
	 */
	public static String requestPostHttp(String strUrl,
			Map<String, Object> params) throws SimpleException {
		String result = "";

		HttpClient httpClient = initHttpClient();

		HttpPost httpPost = new HttpPost(strUrl);
		List<NameValuePair> nvps = new ArrayList<NameValuePair>();
		for (Entry<String, Object> entry : params.entrySet()) {
			if (entry.getValue() != null) {
				nvps.add(new BasicNameValuePair(entry.getKey(), entry
						.getValue().toString()));
			}
		}
		try {
			httpPost.setEntity(new UrlEncodedFormEntity(nvps, encode));
			HttpResponse response = httpClient.execute(httpPost);
			// if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
			// {
			HttpEntity entity = response.getEntity();
			result = EntityUtils.toString(entity, encode);
			// }else{
			//
			// }
		} catch (SocketTimeoutException e) {
			throw SimpleException.newInstance("chaoshi", e);
		} catch (UnknownHostException e) {
			// TODO: handle exception
			throw SimpleException.newInstance("weizhizhuji", e);
		} catch (ParseException e) { // 实体转化为字符串时的异常
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) { // 编码异常
			e.printStackTrace();
		} catch (ClientProtocolException e) { // http 协议异常
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (RuntimeException e) {
			httpPost.abort();
			e.printStackTrace();
		} finally {
			httpClient.getConnectionManager().shutdown();
		}
		return result;
	}

	// public static String encode(String utfString){
	// StringBuilder sb = new StringBuilder();
	// int i = -1;
	// int pos = 0;
	//
	// while((i=utfString.indexOf("\\u", pos)) != -1){
	// sb.append(utfString.substring(pos, i));
	// if(i+5 < utfString.length()){
	// pos = i+6;
	// sb.append((char)Integer.parseInt(utfString.substring(i+2, i+6), 16));
	// }
	// }
	//
	// return sb.toString();
	// }
	public static byte[] getBitmapByte(Bitmap bitmap) {
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
		try {
			out.flush();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return out.toByteArray();
	}

	/**
	 * 文件上传
	 * 
	 * @param actionUrl
	 * @param params
	 * @param files
	 * @return
	 * @throws Exception
	 *             :
	 */
	public static String postBitmap(String actionUrl,
			Map<String, String> params, Map<String, Bitmap> files)
			throws Exception {
		HashMap<String, byte[]> hashMap = new HashMap<String, byte[]>();
		for (Entry<String, Bitmap> entry : files.entrySet()) {
			hashMap.put(entry.getKey(), getBitmapByte(entry.getValue()));
		}
		return post2(actionUrl, params, hashMap);
	}

	/**
	 * 获取httpclient
	 * 
	 * @return
	 */
	private static HttpClient initHttpClient() {
		BasicHttpParams httpParams = new BasicHttpParams();
		HttpConnectionParams.setConnectionTimeout(httpParams, REQUEST_TIMEOUT);
		HttpConnectionParams.setSoTimeout(httpParams, SO_TIMEOUT);
		HttpClient httpClient = new DefaultHttpClient(httpParams);
		return httpClient;
	}

	/**
	 * get 请求
	 * 
	 * @throws SimpleException
	 */
	public static String requestGetHttp(String url, Map<String, Object> params)
			throws SimpleException {
		String combineUrl = url;
		if (params != null) {
			combineUrl = combineUrl(url, params);
		}
		return requestGetHttp(combineUrl);

	}

	/**
	 * 拼接url
	 * 
	 * @param url
	 * @param parms
	 * @return
	 */
	private static String combineUrl(String url, Map<String, Object> parms) {
		int indexOf = url.indexOf("?");
		StringBuilder sb = new StringBuilder(url);
		if (indexOf != -1) {
			sb.append("&");
		} else {
			sb.append("?");
		}
		for (Entry<String, Object> entry : parms.entrySet()) {
			try {
				sb.append(URLEncoder.encode(entry.getKey(), encode))
						.append("=")
						.append(URLEncoder.encode(entry.getValue() == null ? ""
								: entry.getValue().toString(), encode))
						.append("&");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}
		int lastIndexOf = sb.lastIndexOf("&");
		if (lastIndexOf >= 0) {
			sb.deleteCharAt(sb.lastIndexOf("&"));
		}

		return sb.toString();
	}

	/**
	 * get 请求
	 * 
	 * @param strUrl
	 * @return
	 * @throws SimpleException
	 */
	public static String requestGetHttp(String strUrl) throws SimpleException {
		Logs.i("HTTP", "url:  " + strUrl);
		String result = "";
		HttpClient httpClient = initHttpClient();
		HttpGet httpget = null;
		try {
			httpget = new HttpGet(strUrl);
			Logs.d("sport", "strUrl:" + strUrl);
			HttpResponse response = httpClient.execute(httpget);
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				HttpEntity entity = response.getEntity();
				result = EntityUtils.toString(entity, encode);
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (SocketTimeoutException e) {
			throw SimpleException.newInstance("chaoshi", e);
		} catch (ParseException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (RuntimeException e) {
			// In case of an unexpected exception you may want to abort
			// the HTTP request in order to shut down the underlying
			// connectigon immediately.
			e.printStackTrace();
			if (httpget != null)
				httpget.abort();
		} finally {
			// When HttpClient instance is no longer needed,
			// shut down the connection manager to ensure
			// immediate deallocation of all system resources
			httpClient.getConnectionManager().shutdown();
		}
		return result;
	}

	/**
	 * 读取字节流
	 * 
	 * @param in
	 * @return
	 */
	private static String getString(InputStream in) {
		BufferedReader reader = new BufferedReader(new InputStreamReader(in));
		StringBuilder sb = new StringBuilder();
		String line = null;
		try {
			while ((line = reader.readLine()) != null) {
				sb.append(line);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return sb.toString();
	}

	/**
	 * 文件上传
	 * 
	 * @param actionUrl
	 * @param params
	 * @param files
	 * @return
	 * @throws Exception
	 */
	public static String postFile(String actionUrl, Map<String, String> params,
			Map<String, byte[]> files) throws Exception {
		StringBuilder sb2 = null;
		String BOUNDARY = java.util.UUID.randomUUID().toString();
		String PREFIX = "--", LINEND = "\r\n";
		String MULTIPART_FROM_DATA = "multipart/form-data";
		String CHARSET = encode;

		URL uri = new URL(actionUrl);
		HttpURLConnection conn = (HttpURLConnection) uri.openConnection();
		conn.setReadTimeout(6 * 1000); // 缓存的最长时
		conn.setDoInput(true);// 允许输入
		conn.setDoOutput(true);// 允许输出
		conn.setUseCaches(false); // 不允许使用缓
		conn.setRequestMethod("POST");
		conn.setRequestProperty("connection", "keep-alive");
		conn.setRequestProperty("Charsert", encode);
		conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA
				+ ";boundary=" + BOUNDARY);

		// 首先组拼文本类型的参
		StringBuilder sb = new StringBuilder();
		for (Map.Entry<String, String> entry : params.entrySet()) {
			sb.append(PREFIX);
			sb.append(BOUNDARY);
			sb.append(LINEND);
			sb.append("Content-Disposition: form-data; name=\""
					+ entry.getKey() + "\"" + LINEND);
			sb.append("Content-Type: text/plain; charset=" + CHARSET + LINEND);
			sb.append("Content-Transfer-Encoding: 8bit" + LINEND);
			sb.append(LINEND);
			sb.append(entry.getValue());
			sb.append(LINEND);
		}

		DataOutputStream outStream = new DataOutputStream(
				conn.getOutputStream());
		outStream.write(sb.toString().getBytes());

		InputStream in = null;
		// 发文件数据
		if (files != null) {
			for (Map.Entry<String, byte[]> file : files.entrySet()) {
				StringBuilder sb1 = new StringBuilder();
				sb1.append(PREFIX);
				sb1.append(BOUNDARY);
				sb1.append(LINEND);
				sb1.append("Content-Disposition: form-data; name=\"file\"; filename=\""
						+ file.getKey() + "\"" + LINEND);
				sb1.append("Content-Type: application/octet-stream; charset="
						+ CHARSET + LINEND);
				sb1.append(LINEND);
				outStream.write(sb1.toString().getBytes());

				outStream.write(file.getValue());

				outStream.write(LINEND.getBytes());
			}
		}
		// 请求结束标志
		byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();
		outStream.write(end_data);
		outStream.flush();
		// 得到响应
		int res = conn.getResponseCode();
		sb2 = new StringBuilder();
		if (res == 200) {
			in = conn.getInputStream();
			int ch;
			while ((ch = in.read()) != -1) {
				sb2.append((char) ch);
			}
			// System.out.println(sb2.toString());
		} else {
			sb2.append("fail");
		}
		outStream.close();
		conn.disconnect();
		// 解析服务器返回来的数
		return sb2.toString();
	}

	/**
	 * 带文件表单上传
	 * 
	 * @param actionUrl
	 * @param params
	 * @param files
	 * @return
	 * @throws IOException
	 */
	public static String post(String actionUrl, Map<String, String> params,
			Map<String, File> files) throws IOException {

		String BOUNDARY = java.util.UUID.randomUUID().toString();
		String PREFIX = "--", LINEND = "\r\n";
		String MULTIPART_FROM_DATA = "multipart/form-data";
		String CHARSET = encode;
		URL uri = new URL(actionUrl);
		Logs.d("sport", "actionUrl:" + actionUrl);
		HttpURLConnection conn = (HttpURLConnection) uri.openConnection();
		conn.setReadTimeout(5 * 1000);
		conn.setDoInput(true);// 允许输入
		conn.setDoOutput(true);// 允许输出
		conn.setUseCaches(false);
		conn.setRequestMethod("POST"); // Post方式
		conn.setRequestProperty("connection", "keep-alive");
		conn.setRequestProperty("Charsert", encode);
		conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA
				+ ";boundary=" + BOUNDARY);

		// 首先组拼文本类型的参
		StringBuilder sb = new StringBuilder();
		for (Map.Entry<String, String> entry : params.entrySet()) {
			sb.append(PREFIX);
			sb.append(BOUNDARY);
			sb.append(LINEND);
			sb.append("Content-Disposition: form-data; name=\""
					+ entry.getKey() + "\"" + LINEND);
			sb.append("Content-Type: text/plain; charset=" + CHARSET + LINEND);
			sb.append("Content-Transfer-Encoding: 8bit" + LINEND);
			sb.append(LINEND);
			sb.append(entry.getValue());
			sb.append(LINEND);
			Logs.d("sport", "开始sb:" + sb);
		}

		DataOutputStream outStream = new DataOutputStream(
				conn.getOutputStream());

		outStream.write(sb.toString().getBytes());

		// 发文件数据
		if (files != null) {
			for (Map.Entry<String, File> file : files.entrySet()) {
				StringBuilder sb1 = new StringBuilder();
				sb1.append(PREFIX);
				sb1.append(BOUNDARY);
				sb1.append(LINEND);
				sb1.append("Content-Disposition: form-data; name=\"file\"; filename=\""
						+ file.getKey() + "\"" + LINEND);
				sb1.append("Content-Type: application/octet-stream; charset="
						+ CHARSET + LINEND);
				sb1.append(LINEND);
				Logs.d("sport", "文件sb1:" + sb1);
				outStream.write(sb1.toString().getBytes());

				InputStream is = new FileInputStream(file.getValue());
				byte[] buffer = new byte[1024];
				int len = 0;
				while ((len = is.read(buffer)) != -1) {
					outStream.write(buffer, 0, len);
				}

				is.close();
				outStream.write(LINEND.getBytes());
				Logs.d("sport", "写完流sb:" + sb);
			}
		}
		// 请求结束标志
		byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();
		outStream.write(end_data);
		outStream.flush();

		// 得到响应
		String res = "Fail";
		if (conn.getResponseCode() == HttpStatus.SC_OK) {
			InputStream in = conn.getInputStream();
			res = getString(in);
		}
		outStream.close();
		conn.disconnect();
		return res;
	}

	/**
	 * post 请求httpurlconnection
	 * 
	 * @param actionUrl
	 * @param params
	 * @return
	 * @throws IOException
	 */
	public static String post(String actionUrl, Map<String, String> params)
			throws IOException {
		HttpURLConnection conns = null;
		DataOutputStream outStream;
		String BOUNDARY = java.util.UUID.randomUUID().toString();
		String PREFIX = "--";
		String LINEND = "\r\n";
		String MULTIPART_FROM_DATA = "multipart/form-data";
		String CHARSET = encode;
		URL uri = new URL(actionUrl);
		conns = (HttpURLConnection) uri.openConnection();
		conns.setReadTimeout(5000);
		conns.setConnectTimeout(5000);
		conns.setDoInput(true);
		conns.setDoOutput(true);
		conns.setUseCaches(false);
		conns.setRequestMethod("POST");
		conns.setRequestProperty("connection", "keep-alive");
		conns.setRequestProperty("Charsert", encode);
		conns.setRequestProperty("Content-Type", MULTIPART_FROM_DATA
				+ ";boundary=" + BOUNDARY);
		StringBuilder sb = new StringBuilder();
		if (params != null) {
			for (Map.Entry<String, String> entry : params.entrySet()) {
				sb.append(PREFIX);
				sb.append(BOUNDARY);
				sb.append(LINEND);
				sb.append("Content-Disposition: form-data; name=\""
						+ entry.getKey() + "\"" + LINEND);
				sb.append("Content-Type: text/plain; charset=" + CHARSET
						+ LINEND);
				sb.append("Content-Transfer-Encoding: 8bit" + LINEND);
				sb.append(LINEND);
				sb.append(entry.getValue());
				sb.append(LINEND);
			}
		}
		outStream = new DataOutputStream(conns.getOutputStream());
		outStream.write(sb.toString().getBytes());
		byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();
		outStream.write(end_data);
		outStream.flush();
		int res = conns.getResponseCode();
		String reStr = "";
		if (res != 200) {
			reStr = "conn.getResponseCode()" + ":" + String.valueOf(res);
		} else {
			InputStream in = conns.getInputStream();
			int ch;
			StringBuilder sb2 = new StringBuilder();
			while ((ch = in.read()) != -1) {
				sb2.append((char) ch);
			}
			reStr = sb2.toString();
			in.close();
		}
		outStream.close();
		conns.disconnect();
		return reStr;
	}

	/**
	 * 带文件表单上传
	 * 
	 * @param actionUrl
	 * @param params
	 * @return
	 * @throws IOException
	 */
	public static String post2(String actionUrl, Map<String, String> params,
			Map<String, byte[]> files) throws IOException {

		String BOUNDARY = java.util.UUID.randomUUID().toString();
		String PREFIX = "--", LINEND = "\r\n";
		String MULTIPART_FROM_DATA = "multipart/form-data";
		String CHARSET = encode;
		URL uri = new URL(actionUrl);
		Logs.d("sport", "actionUrl:" + actionUrl);
		HttpURLConnection conn = (HttpURLConnection) uri.openConnection();
		conn.setReadTimeout(5 * 1000);
		conn.setDoInput(true);// 允许输入
		conn.setDoOutput(true);// 允许输出
		conn.setUseCaches(false);
		conn.setRequestMethod("POST"); // Post方式
		conn.setRequestProperty("connection", "keep-alive");
		conn.setRequestProperty("Charsert", encode);
		conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA
				+ ";boundary=" + BOUNDARY);

		// 首先组拼文本类型的参
		StringBuilder sb = new StringBuilder();
		for (Map.Entry<String, String> entry : params.entrySet()) {
			sb.append(PREFIX);
			sb.append(BOUNDARY);
			sb.append(LINEND);
			sb.append("Content-Disposition: form-data; name=\""
					+ entry.getKey() + "\"" + LINEND);
			sb.append("Content-Type: text/plain; charset=" + CHARSET + LINEND);
			sb.append("Content-Transfer-Encoding: 8bit" + LINEND);
			sb.append(LINEND);
			sb.append(entry.getValue());
			sb.append(LINEND);
			Logs.d("sport", "开始sb:" + sb);
		}

		DataOutputStream outStream = new DataOutputStream(
				conn.getOutputStream());

		outStream.write(sb.toString().getBytes());

		// 发文件数据
		if (files != null) {
			for (Map.Entry<String, byte[]> file : files.entrySet()) {
				StringBuilder sb1 = new StringBuilder();
				sb1.append(PREFIX);
				sb1.append(BOUNDARY);
				sb1.append(LINEND);
				sb1.append("Content-Disposition: form-data; name=\"file\"; filename=\""
						+ file.getKey() + "\"" + LINEND);
				sb1.append("Content-Type: application/octet-stream; charset="
						+ CHARSET + LINEND);
				sb1.append(LINEND);
				Logs.d("sport", "文件sb1:" + sb1);
				outStream.write(sb1.toString().getBytes());

				outStream.write(file.getValue());

				outStream.write(LINEND.getBytes());
				Logs.d("sport", "写完流sb:" + sb);
			}
		}
		// 请求结束标志
		byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();
		outStream.write(end_data);
		outStream.flush();

		// 得到响应
		String res = "Fail";
		if (conn.getResponseCode() == HttpStatus.SC_OK) {
			InputStream in = conn.getInputStream();
			res = getString(in);
		}
		outStream.close();
		conn.disconnect();
		return res;
	}

	public static String uploadFile(String url, Post5_14 params)
			throws Exception {
		HttpClient httpClient = new DefaultHttpClient();
		HttpPost post = new HttpPost(url);

		FileBody fb = new FileBody(new File(params.getFile()));
		MultipartEntity entity = new MultipartEntity();

		entity.addPart("file", fb);
		entity.addPart("type", new StringBody(params.getType()));
		entity.addPart("AccessKey", new StringBody(params.getAccessKey()));
		entity.addPart("SessionID", new StringBody(params.getSessionID()));
		post.setEntity(entity);

		System.out.println("开始上传");
		HttpResponse response = httpClient.execute(post);
		int code = response.getStatusLine().getStatusCode();
		if (code == HttpStatus.SC_OK) {
			HttpEntity resEntity = response.getEntity();
			String str = EntityUtils.toString(resEntity);
			InputStream content = resEntity.getContent();

			System.out.println(content.toString());

			// EntityUtils.consume(resEntity);
			return str;
		} else {
			// 测试提交
			System.out.println("失败");
		}
		return "qunima ";
	}

}

class Logs {
	public static void i(String tag, String msg) {
		System.out.println(tag + ":\t" + msg);
	}

	public static void e(String tag, String msg) {
		System.out.println(tag + ":\t" + msg);
	}

	public static void d(String tag, String msg) {
		System.out.println(tag + ":\t" + msg);
	}
}
